﻿using System;
using System.Linq;
using System.Dynamic;
using System.IO;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Web.Http;
using System.Web;
using MVCProject.Model;
using MVCProject.BLL;
using System.Runtime.InteropServices;

namespace MVCProject.API.Controllers
{
    public class FilesController : ApiController
    {
        public ResultData<ImagesDto> Upload()
        {
            ResultData<ImagesDto> result = new ResultData<ImagesDto>();

            //获取提交的文件
            var files = HttpContext.Current.Request.Files;
            var file = files[0];
            if (files.Count < 1 || file == null)
            {
                result.code = -4;
                result.msg = "上传失败，未检测上传的文件信息!";
            }
            else
            {
                //获取当前时间
                var currentDate = DateTime.Now;
                //获取系统的根路径
                var webRootPath = HttpContext.Current.Server.MapPath("/");
                try
                {
                    //文件后缀//获取文件格式，拓展名
                    var fileExtension = Path.GetExtension(file.FileName).ToLower();
                    var type = "";

                    //获取 web.config 配置文件中配置数据
                    string imgType = ConfigurationManager.AppSettings["imgtype"];
                    string audioType = ConfigurationManager.AppSettings["audiotype"];
                    string videoType = ConfigurationManager.AppSettings["videotype"];
                    string officeType = ConfigurationManager.AppSettings["officetype"];
                    string fileType = ConfigurationManager.AppSettings["filetype"];
                    //根据后缀匹配相应的文件夹
                    type = Regex.IsMatch(fileExtension, imgType) ? "img"
                           : Regex.IsMatch(fileExtension, audioType) ? "audio"
                           : Regex.IsMatch(fileExtension, videoType) ? "video"
                           : Regex.IsMatch(fileExtension, officeType) ? "office"
                           : Regex.IsMatch(fileExtension, fileType) ? "file"
                           : "";

                    //判断是否有当前日期文件夹
                    var filePath = $"/UploadFiles/{type}/{currentDate:yyyyMMdd}/";
                    if (!Directory.Exists(webRootPath + filePath))
                    {
                        //创建每日存储文件夹
                        Directory.CreateDirectory(webRootPath + filePath);
                    }
                    //判断文件夹不为空时进入
                    if (filePath != null)
                    {

                        var fileSize = file.ContentLength;
                        int maxSize = int.Parse(ConfigurationManager.AppSettings["filemaxsize"]);
                        //判断文件大小
                        if (fileSize > maxSize)
                        {
                            result.code = -2;
                            result.msg = "上传的文件不能大于" + (maxSize / 1024 / 1024) + "M!";
                        }
                        else
                        {
                            //保存的文件名称(以名称和保存时间命名)
                            var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" +
                                currentDate.ToString("HHmmss") + fileExtension;

                            //保存文件到指定路径（完整路径）
                            file.SaveAs(webRootPath + filePath + saveName);

                            //完整的文件路径
                            var completeFilePath = Path.Combine(filePath, saveName);

                            //将图片路径保存到 图片管理表中
                            Images images = new Images();
                            images.imgID = 0;
                            images.path = completeFilePath;
                            images.extension = fileExtension;
                            images.size = fileSize;
                            images.title = saveName;
                            images.modular = 1;
                            images.lastTime = DateTime.Now;

                            ImagesBll bll= new ImagesBll();
                            var img = bll.Insert(images);

                            ImagesDto dataDto = new ImagesDto();
                            dataDto.ImgID = img.imgID;
                            dataDto.Path = img.path; 
                            dataDto.Extension = img.extension; 
                            dataDto.Size = img.size; 
                            dataDto.Title = img.title; 
                            dataDto.Modular = img.modular; 
                            dataDto.LastTime = img.lastTime; 


                            result.code = 1;
                            result.msg = "上传成功!";
                            result.data = dataDto;
                        }
                    }
                    else
                    {
                        result.code = -3;
                        result.msg = "创建文件夹失败!";
                    }
                }
                catch (Exception ex)
                {
                    result.code = -5;
                    result.msg = "文件保存失败，异常信息为：" + ex.Message;

                }
            }

            return result;
        }
    }
}